package com.tencet.dao.impl;

import com.tencet.dao.WithdrawalDAO;
import com.tencet.utils.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.awt.*;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author: @date: 2022/7/20 21:46 A
 * @description: 提现
 */
public class WithdrawalDAOImpl implements WithdrawalDAO {

    private QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());

    //通过二类卡号查询卡中余额
    @Override
    public int getBalance(String card2_num) {
        String sql = "select balance from bank_account2 where card_num=?";

        try {

            int balance = (int) qr.query(sql, new ScalarHandler(), card2_num);
            return balance;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    //通过手机号查询此人的所有一类卡
    @Override
    public List getCard_num(String p_phone) {
        String sql = "select secondaccountnumber from openaccount where phone=?";

        try {

            List account_id1s = (List) qr.query(sql, new ScalarHandler(), p_phone);
            return account_id1s;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    //通过二类卡号查询此卡交易密码
    @Override
    public String getPassword(String phone) {
        String sql = "select paypassword from openaccount where phone=?";

        try {

            String password = (String) qr.query(sql, new ScalarHandler(), phone);
            System.out.println("p"+password);
            return password;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return "没找到二类卡密码";
    }


    //通过一二类卡号以及转账金额更改余额
    @Override
    public boolean changeBalance(int money, String account_id1, String card2_num) {

        try {
            //更改二类卡余额
            String sql = "select balance from bank_account2 where card_num=?";

            int balance = (int) qr.query(sql, new ScalarHandler(), card2_num);
            int newBalance = balance - money;
            String sql1 = "update bank_account2 set balance = ? where card_num =?";
            qr.update(sql1, newBalance, card2_num);

            //更改一类卡余额
            String sql2 = "select balance from bank_account1 where card_num=?";
            balance = (int) qr.query(sql2, new ScalarHandler(), account_id1);
            newBalance = balance + money;
            String sql3 = "update bank_account1 set balance = ? where card_num =?";
            qr.update(sql3, newBalance, account_id1);
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                JDBCUtils.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
        return false;
    }
}